package com.bdqn.t362.common.utils;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


/**
 * @author lqm
 * @ClassName EmailUtil
 * @description: TODO
 */
public class EmailUtil {
    // 发件人电子邮箱
    final static String from = "1026132244@qq.com";

    // 发件人电子邮箱
    final static String pwd = "akjgvwebfjiqbccj";
    // 指定发送邮件的主机为 smtp.qq.com
    final static String host = "smtp.qq.com";  //QQ 邮件服务器

    public static boolean sendEmail(String toEmail, String titleStr, String bodyStr) {
        boolean resultBool =false;


        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, pwd); //发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));

            // Set Subject: 标题
            message.setSubject(titleStr);

            // 设置消息体
            message.setText(bodyStr);

            // 发送消息
            Transport.send(message);
            resultBool=true;
            System.out.println("Sent message successfully....from runoob.com");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return resultBool;
    }


    public static void main(String[] args) {
        String codeStr = String.valueOf((int) ((Math.random()*9+1)*1000));
        sendEmail("1026132244@qq.com","发送验证码","您的验证码是："+codeStr);
    }

}
